<template>
  <div>
    <!-- 页面标题区域 -->
    <div class="page-header">
      <h1>用户管理</h1>
      <div class="header-actions">
        <button class="btn-create" @click="openUserModal">创建用户</button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search_box">
      <el-card>
        <el-tabs v-model="queryInfo.is_fictitious" class="demo-tabs" @tab-click="searchTable">
          <el-tab-pane :label="item.label" :name="item.value" v-for="item in userTypes" :key="item.value"></el-tab-pane>
        </el-tabs>

        <div class="flex align-center">
          <el-input v-model="queryInfo.phone" style="width: 300px;" class="m-2" size="large" placeholder="搜索用户账号或昵称"
                    :prefix-icon="Search" @change="searchTable" />
        </div>
      </el-card>
    </div>

    <!-- 表格区域 -->
    <div class="margin-top">
      <el-table ref="multipleTableRef" :data="listData" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column property="id" label="用户ID" width="100"></el-table-column>

        <el-table-column label="账号" property="phone">
          <template #default="scope">
            <div>ID：{{ scope.row.id }}</div>
            <div style="color:red">账号信息：{{ scope.row.phone }}</div>
            <div>昵称：{{ scope.row.user_name }}</div>
            <div style="color:red">余额：{{ scope.row.money_balance }}</div>
          </template>
        </el-table-column>

<!--        <el-table-column property="user_name" label="用户" width="200"></el-table-column>-->

        <el-table-column label="用户类型">
          <template #default="scope">
            <template v-for="item in userTypes">
              <el-tag class="ml-2" :key="item.id" :color="item.color" v-if="scope.row.is_fictitious === item.value">
                {{ item.label }}
              </el-tag>
            </template>
          </template>
        </el-table-column>

<!--        <el-table-column label="余额" property="money_balance"></el-table-column>-->

        <!-- <el-table-column label="电子邮箱" property="email"></el-table-column> -->
        <el-table-column label="上级信息" property="agent" >
          <template #default="scope">
            <div v-if="scope.row.agent_info?.id > 0">
              <div> ID： {{ scope.row.agent_info?.id }}</div>
              <div>账号： {{ scope.row.agent_info?.phone }}</div>
              <div>昵称： {{ scope.row.agent_info?.user_name }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="佣金比例" property="commission_rate"
                         v-if="queryInfo.is_fictitious == 1 || queryInfo.is_fictitious == 3">
          <template #default="scope">
            <div>{{
                scope.row.userConfigWithOne?.commission_rate ?
                  (scope.row.userConfigWithOne.commission_rate * 100).toFixed(0)
                  :
                  0 }}%</div>
          </template>
        </el-table-column>

        <el-table-column property="status" label="状态">
          <template #default="scope">
            <template v-for="item in userStatus">
              <el-tag class="ml-2" :key="item.id" :type="item.type" v-if="scope.row.status === item.value">
                {{ item.label }}
              </el-tag>
            </template>
          </template>
        </el-table-column>

        <el-table-column label="订单信息" property="phone">
          <template #default="scope">
            <div style="color:red">总订单金额：{{ scope.row.goods_pay?.payMoney || 0}}</div>
            <div style="color:blue">总实际到账金额：{{ scope.row.goods_pay?.netMoney || 0}}</div>
            <div>总订单数：{{ scope.row.goods_pay?.CountID || 0}}</div>
            <div style="color:red">月订单金额：{{ scope.row.goods_month_pay?.payMoney || 0}}</div>
            <div style="color:blue">月实际到账金额：{{ scope.row.goods_month_pay?.netMoney || 0}}</div>
            <div>月订单数：{{ scope.row.goods_month_pay?.CountID || 0}}</div>

          </template>
        </el-table-column>

        <el-table-column label="操作" width="400">
          <template #default="scope">
            <div class="flex align-center">
              <el-button size="small" @click="openUserModal(scope.row)">编辑</el-button>

              <el-button size="small" @click="handleSetUserBalance(scope.row)">余额修改</el-button>

              <span class="flex margin-left-xs">
                <el-button size="small" type="success" @click="handleUserStatus(scope.row, '1')"
                           v-if="scope.row.status == 0">启用</el-button>

                <el-button size="small" type="info" @click="handleUserStatus(scope.row, '0')" v-else>禁用</el-button>
              </span>

              <el-button class="margin-left-xs" size="small" type="info"
                         @click="handleSetUserBrokerage(scope.row)">佣金设置</el-button>

              <el-button class="margin-left-xs" size="small" type="primary"
                         @click="viewUserDetails(scope.row)">查看详情</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="margin-top">
      <Pagination :total="total" @change="changePage" />
    </div>

    <!-- 用户表单 -->
    <UserFormModal ref="userFormModalRef" :userTypeData="userTypes" :userStatusData="userStatus"
                   @reload="searchTable" />

    <UserBrokerageFormModal @reload="searchTable" ref="userBrokerageFormModalRef" />
  </div>

  <div>
    <el-dialog v-model="visible" :show-close="false">

      <h4>余额增减----用户余额 ( {{balanceUser}} )</h4>
      <div>
        <el-form  label-width="120px" ref="elFormRef">
          <el-form-item label="输入金额" prop="aa">
            <el-input v-model="balanceMoney"  type="number"  @input="handleAmountInput" @blur="formatFinalValue"/>
          </el-form-item>
		  <el-form-item label="状态" prop="status">
		    <Select v-model="banalceType" :data="banalceTypeStatus" />
		  </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="close">关闭</el-button>

          <el-button type="primary" @click="handleSubmit">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, toRef, onMounted, watch } from 'vue'
import Select from '@/components/admin/Select.vue'
import { useRoute } from 'vue-router'
import { useRouter } from 'vue-router';
import useTableHook from '@/hooks/useTableHook'
import { GetUserList, UserAddAndEdit ,SetUserBalance} from '@/api/index'
import { RefreshRight } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Pagination from '@/components/admin/Pagination.vue'
import UserFormModal from '@/components/admin/users/UserFormModal.vue';
import UserBrokerageFormModal from '@/components/admin/users/UserBrokerageFormModal.vue'

const router = useRouter();

// 用户表单
const userFormModalRef = ref()

const openUserModal = (data = {}) => {
  userFormModalRef.value.open({
    data: {
      ...data,
      classId: data.is_fictitious
    }
  })
}

// ------------

const userTypes = [
  {
    label: '全部',
    value: ''
  },
  {
    label: '区域代理',
    value: 1,
  },
  // {
  //   label: '店铺',
  //   value: 2,
  // },
  {
    label: '经销商',
    value: 3,
  },
  {
    label: '普通用户',
    value: 0
  },
]

const userStatus = [
  {
    label: '冻结',
    value: 0,
    type: 'error'
  },
  {
    label: '正常',
    value: 1,
    type: 'success'
  }
]

const statusData = [
  {
    label: '全部状态',
    value: ''
  },
  {
    label: '待发货',
    value: 0,
    color: '#f4f4f5'
  },
  {
    label: '发货中',
    value: 1,
    color: '#409eff'
  },
  {
    label: '代签收',
    value: 2,
    color: '#e6a23c'
  },
  {
    label: '已签收',
    value: 3,
    color: '#66c03a'
  },
  {
    label: '结束订单',
    value: 4,
    color: '#909399'
  },
  {
    label: '取消订单',
    value: 5,
    color: '#f56c6c'
  }
]

const queryInfo = ref({
  is_fictitious: '',
  phone: '',
  status: '',
  page: 1,
  limit: 10,
})

const userBrokerageFormModalRef = ref()

// 设置佣金比例
const handleSetUserBrokerage = (record) => {
  userBrokerageFormModalRef.value.open({
    data: {
      uid: record.id
    }
  }, 'edit')
}
const visible = ref(false)


const close = () => {
  visible.value = false
}

// 设置用户余额
const handleSetUserBalance = (record) => {
  balanceUerID.value =record.id
  balanceUser.value = record.money_balance
  banalceType.value = 0
   balanceMoney.value = 0
 visible.value = true
}

const handleUserStatus = (record, status) => {
  let statusText = record.status == 1 ? '禁用' : '启用'

  ElMessageBox.confirm(`确认${statusText}用户: ${record.user_name}`, {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(async () => {
    try {
      let newVal = JSON.parse(JSON.stringify(record))

      newVal.status = status

      newVal.method = 'edit'

      const res = await UserAddAndEdit(newVal)

      ElMessage({
        type: 'success',
        message: `${statusText}成功!`
      })

      searchTable()
    } catch (err) {
      ElMessage({
        type: 'error',
        message: `${statusText}失败!`,
      })
    }
  })
}

// 查看用户详情
const viewUserDetails = (user: any) => {
  // 跳转到用户详情页面
  router.push(`/admin/users/${user.id}`);
};

const balanceMoney = ref(0)
const banalceType =  ref(0)
const balanceUser =  ref(0)
const balanceUerID =  ref(0)
const banalceTypeStatus = [
  { label: '增加', value: 1 },
  { label: '减少', value: 2 }
]
// 实时输入过滤
const handleAmountInput = (value) => {
  // 1. 只允许数字和小数点
  let filtered = value.replace(/[^\d.]/g, '')

  // 2. 禁止多个小数点
  if ((filtered.match(/\./g) || []).length > 1) {
    filtered = filtered.substring(0, filtered.lastIndexOf('.'))
  }

  // 3. 禁止整数部分以0开头（除非是0本身或0.xxx）
  if (/^0[^.]/.test(filtered)) {
    filtered = filtered.substring(1)
  }

  balanceMoney.value = filtered
}

// 失焦时格式化最终值
const formatFinalValue = () => {
  if (balanceMoney.value === '') return

  // 1. 补全".0" => "0.0"
  if (balanceMoney.value.startsWith('.')) {
    balanceMoney.value = '0' + balanceMoney.value
  }

  // 2. 去除末尾小数点（"123." => "123"）
  if (balanceMoney.value.endsWith('.')) {
    balanceMoney.value = balanceMoney.value.slice(0, -1)
  }

  // 3. 强制数字类型转换（避免字符串）
  balanceMoney.value = Number(balanceMoney.value).toString()
}
const handleSubmit = async () => {

  if (banalceType.value <= 0|| balanceMoney.value <= 0|| balanceUerID.value <= 0){
    ElMessage({
      message: `参数错误!`,
      type: 'error'
    })
    return
  }
  try {
  //   // formData.value.method = formType.value
    const res = await SetUserBalance({type:banalceType.value,money:balanceMoney.value,uid:balanceUerID.value})
    ElMessage({
      message: `设置余额成功!`,
      type: 'success'
    })
  searchTable()
  //   elFormRef.value.resetFields()

  //   emit('reload')
    close()
  } catch (err) {
    console.log(err)
    ElMessage({
      message: '设置余额失败!',
      type: 'error'
    })
  }
}

onMounted(() => {
  initTable()
})

const {
  total,
  listData,
  searchTable,
  initTable,
  changePage,
} = useTableHook(queryInfo.value, GetUserList)
</script>

<style lang="scss">
$primary: #3498db;

/* 头部区域样式 */
/* 页面标题区域 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background-color: white;
  padding: 20px 24px;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.04);
}

.page-header h1 {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
  position: relative;
}

.page-header h1::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: -8px;
  width: 40px;
  height: 3px;
  background-color: $primary;
  border-radius: 3px;
}

.btn-create {
  background-color: $primary;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-create:hover {
  background-color: darken($primary, 10%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(66, 153, 225, 0.3);
}

.btn-create::before {
  content: '+';
  font-size: 18px;
  font-weight: 500;
}

.title-section {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  color: #2c3e50;
}

.merchant-name {
  color: #e74c3c;
}

.back-link {
  display: inline-flex;
  align-items: center;
  font-size: 14px;
  color: #7f8c8d;
  text-decoration: none;
  transition: color 0.3s;
  margin-top: 5px;
}

.back-link:hover {
  color: #e74c3c;
}

.back-link i {
  margin-right: 5px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.btn-primary {
  background-color: #e74c3c;
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  font-weight: 600;
  transition: background-color 0.3s;
}

.btn-primary:hover {
  background-color: #c0392b;
}

.btn-primary i {
  margin-right: 5px;
}
</style>
